package vip.huhailong.slicefile.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

@RestController
@RequestMapping("/file")
public class FileController {

  @Value("${upload.dir}")
  private String uploadDir;

  @PostMapping("/uploadBySlice")
  public String uploadBySlice(MultipartFile file, String fileName, String uid, long currentIndex) throws IOException {
    mkdirUploadDir();
    String filePath = uploadDir + uid+"-"+fileName;
    try (RandomAccessFile accessFile = new RandomAccessFile(filePath, "rw")) {
      accessFile.seek(currentIndex);
      System.out.println("Thread name:"+Thread.currentThread().getName()+";currentIndex:" + currentIndex + "; fileSize:" + file.getBytes().length);
      accessFile.write(file.getBytes());
      return "Thread name:"+Thread.currentThread().getName()+";currentIndex:" + currentIndex + "; fileSize:" + file.getBytes().length;
    }
  }

  private void mkdirUploadDir() {
    File uploadDirFile = new File(uploadDir);
    if (!uploadDirFile.exists()) {
      boolean mkdirs = uploadDirFile.mkdirs();
      if (!mkdirs) {
        throw new RuntimeException("创建上传目录失败");
      }
    }
  }
}
